<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Collect telemetry using Application Insights</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!--
      This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to using Web Chat's latest bits:
      https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
    -->
    <script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
      html,
      body {
        height: 100%;
      }

      body {
        margin: 0;
      }

      #webchat {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="webchat" role="main"></div>
    <script>
      var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(e){function n(e){t[e]=function(){var n=arguments;t.queue.push(function(){t[e].apply(t,n)})}}var t={config:e};t.initialize=!0;var i=document,a=window;setTimeout(function(){var n=i.createElement("script");n.src=e.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js",i.getElementsByTagName("script")[0].parentNode.appendChild(n)});try{t.cookie=i.cookie}catch(e){}t.queue=[],t.version=2;for(var r=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];r.length;)n("track"+r.pop());n("startTrackPage"),n("stopTrackPage");var s="Track"+r[0];if(n("start"+s),n("stop"+s),n("setAuthenticatedUserContext"),n("clearAuthenticatedUserContext"),n("flush"),!(!0===e.disableExceptionTracking||e.extensionConfig&&e.extensionConfig.ApplicationInsightsAnalytics&&!0===e.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){n("_"+(r="onerror"));var o=a[r];a[r]=function(e,n,i,a,s){var c=o&&o(e,n,i,a,s);return!0!==c&&t["_"+r]({message:e,url:n,lineNumber:i,columnNumber:a,error:s}),c},e.autoExceptionInstrumented=!0}return t}(
      {
        instrumentationKey:"INSTRUMENTATION_KEY"
      }
      );window[aiName]=aisdk,aisdk.queue&&0===aisdk.queue.length&&aisdk.trackPageView({});
    </script>
    <script>
      (async function() {
        // In this demo, we are using Direct Line token from MockBot.
        // Your client code must provide either a secret or a token to talk to your bot.
        // Tokens are more secure. To learn about the differences between secrets and tokens
        // and to understand the risks associated with using secrets, visit https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0

        const res = await fetch('https://hawo-mockbot4-token-app.blueriver-ce85e8f0.westus.azurecontainerapps.io/api/token/directline', { method: 'POST' });
        const { conversationID, token, userID } = await res.json();

        const telemetryInitializer = () => {
          const { content: webChatUIVersion } =
            document.querySelector('head meta[name="botframework-webchat:ui:version"]') || {};

          appInsights.properties.context.application.ver = webChatUIVersion;
          appInsights.properties.context.session.acquisitionDate = Date.now();
          appInsights.properties.context.session.id = conversationID;
          appInsights.properties.context.user.accountId = userID;
        };

        aisdk.queue ? aisdk.queue.push(telemetryInitializer) : telemetryInitializer();

        const handleTelemetry = event => {
          const { data, dimensions, duration, error, fatal, level, name, type } = event;
          const fullName = `webchatui:${name}`;

          console.group(`onTelemetry ("${type}")`);
          console.log({ name, data, dimensions, duration, error });
          console.groupEnd();

          if (type === 'event') {
            // "event.data" could be a non-negative finite number, a string, or a map with multiple values.
            // When we track them on Application Insights, we will prefix them for categorization.
            const appInsightsData =
              typeof data === 'number' || typeof data === 'string'
                ? { [name]: data }
                : Object.entries(data || {}).reduce(
                    (data, [key, value]) => ({ ...data, [`${name}:${key}`]: value }),
                    {}
                  );

            appInsights.trackEvent({
              name: fullName,
              properties: {
                ...dimensions,
                ...appInsightsData,
                'webchat:level': level
              }
            });
          } else if (type === 'exception') {
            appInsights.trackException({ exception: error });
          } else if (type === 'timingstart') {
            appInsights.startTrackEvent(fullName);
          } else if (type === 'timingend') {
            // Application Insights modify the "dimensions" argument. We need to clone it to prevent it from being modified.
            appInsights.stopTrackEvent(fullName, { ...dimensions });
          }
        };

        window.WebChat.renderWebChat(
          {
            directLine: window.WebChat.createDirectLine({ token }),
            onTelemetry: handleTelemetry
          },
          document.getElementById('webchat')
        );

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
  </body>
</html>
